﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class views_login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["user"] != null)
            {
                Response.Write(@"<script language='javascript'>alert('Đã đăng nhập, Chuyển tới trang chủ!');</script>");
                Response.Write("<script>window.open('../index.aspx','_parent');</script>");
            }
        }
    }
    protected void btnok_Click(object sender, EventArgs e)
    {
        if (check_login() == true)
        {
             
            if (Request.QueryString["log"] != null)
            {
                if (Request.QueryString["log"].ToString().Trim() == "true")
                    Response.Write("<script>window.open('../index.aspx','_parent');</script>");
                else if (Request.QueryString["log"] != null && Request.QueryString["log"].ToString().Trim() == "cart")
                    Response.Write("<script>window.open('../index.aspx?Cart=true','_parent');</script>");
            }
        }
        else
        {
            Response.Write(@"<script language='javascript'>alert('Đăng nhập thất bại!\nXin thử lại!');</script>");
        }
    }
    private bool check_login()
    {
        DataProvider data = new DataProvider();
        SqlConnection conn = data.Connect();
        DataTable dt = new DataTable();
        try
        {
            SqlCommand cmd = new SqlCommand("sp_login", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@username", txtusername.Text);
            cmd.Parameters.AddWithValue("@password", data.encryptData(txtpassword.Text));
            dt.Load(cmd.ExecuteReader());

            if (dt.Rows.Count > 0)
            {
                Session["user"] = dt;
                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
        finally { conn.Close(); }
    }
}